<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="algorithm," />










<meta name="description" content="素数筛选法 素数筛选法的目的就是筛选出在某一区间[m,n)内的所有素数，常见的办法有如下几种。 １.朴素的筛选法朴素的筛选法思路很简单，先写一个判断是否是素数的函数isPrime()，然后从2到n分别调用isPrime()函数来检查。检查是否是质数的算法是核心，使用从2到n的开根的数作为除数（为什么是开根数呢？因为如果当前筛选到p,则说明1p,2p…..(p-1)p已经在筛选1,2,3……p-1的">
<meta property="og:type" content="article">
<meta property="og:title" content="素数筛选法">
<meta property="og:url" content="http://yoursite.com/2020/07/20/%E7%B4%A0%E6%95%B0%E7%AD%9B%E9%80%89%E6%B3%95/index.html">
<meta property="og:site_name" content="LinRaise&#39;s Blog">
<meta property="og:description" content="素数筛选法 素数筛选法的目的就是筛选出在某一区间[m,n)内的所有素数，常见的办法有如下几种。 １.朴素的筛选法朴素的筛选法思路很简单，先写一个判断是否是素数的函数isPrime()，然后从2到n分别调用isPrime()函数来检查。检查是否是质数的算法是核心，使用从2到n的开根的数作为除数（为什么是开根数呢？因为如果当前筛选到p,则说明1p,2p…..(p-1)p已经在筛选1,2,3……p-1的">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-07-20T16:33:02.000Z">
<meta property="article:modified_time" content="2020-07-20T16:33:02.000Z">
<meta property="article:author" content="LinRaise">
<meta property="article:tag" content="algorithm">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/07/20/素数筛选法/"/>





  <title>素数筛选法 | LinRaise's Blog</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">LinRaise's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/20/%E7%B4%A0%E6%95%B0%E7%AD%9B%E9%80%89%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LinRaise">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LinRaise's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">素数筛选法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-20T16:33:02+00:00">
                2020-07-20
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">Post modified&#58;</span>
              
              <time title="Post modified" itemprop="dateModified" datetime="2020-07-20T16:33:02+00:00">
                2020-07-20
              </time>
            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>素数筛选法</p>
<p>素数筛选法的目的就是筛选出在某一区间[m,n)内的所有素数，常见的办法有如下几种。</p>
<p><strong>１.朴素的筛选法</strong><br>朴素的筛选法思路很简单，先写一个判断是否是素数的函数isPrime()，然后从2到n分别调用isPrime()函数来检查。检查是否是质数的算法是核心，使用从2到n的开根的数作为除数（为什么是开根数呢？因为如果当前筛选到p,则说明1<em>p,2</em>p…..(p-1)<em>p已经在筛选1,2,3……p-1的时候被处理过了，现在我们只需要接着处理p</em>p即可，即要求p<em>p &lt;=n）。复杂度大概是O(n</em>log(n)).虽然复杂度看起来比较和谐，但是显然直觉告诉我们调用函数次数过多。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">bool isPrime(int n)</span><br><span class="line">&#123;</span><br><span class="line">	&#x2F;&#x2F;if we process p turn,then ,2*p,3*p,4*p,....(p-1)*p was processed</span><br><span class="line">	&#x2F;&#x2F;so we begin with p*p &lt; n;</span><br><span class="line"></span><br><span class="line">	int i,sqr &#x3D; sqrt((double)n);</span><br><span class="line">	for(i&#x3D;2; i&lt;&#x3D;sqr; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		if ( (n%i) &#x3D;&#x3D; 0 )</span><br><span class="line">			return false;</span><br><span class="line">	&#125;</span><br><span class="line">	return true;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接下来如果需要找到[m,n)的素数，只需要在[m,n)上调用<code>isPrime()</code>函数n-m次即可。</p>
<p><strong>2.比朴素法更高效的筛选法</strong><br>我们知道要求某一区间内的素数，只需要将这一区间内的合数去除，即筛除即可，这种办法利用的就是这种思想。</p>
<p>例如：2,3,4,5,6,7,8,9,10,11,12,13,14,15…….</p>
<p>第一遍筛掉2的倍数:剩下2,3,5,7,9,11,13,15…..</p>
<p>第二遍筛掉3的倍数:剩下2,3,5,7,11,13,….</p>
<p>第三遍筛掉5的倍数:(为什么是5而不是4,因为4已经被2的倍数筛掉了，再筛已经无意义)</p>
<p>第四遍筛掉7的倍数:(为什么是7而不是6,同理因为6已经被之前的2,3筛掉了再筛也没有意义了)</p>
<p>下面用程序去模拟这个过程：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">#include&lt;iostream&gt;</span><br><span class="line">#include&lt;string&gt;</span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">const int N &#x3D; 30;</span><br><span class="line">int Prime[5000]; &#x2F;&#x2F;保存素数</span><br><span class="line">bool isPrime[5000];&#x2F;&#x2F;标记该位是否是素数</span><br><span class="line">int len;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;fin [2,N] &#39;s prime</span><br><span class="line">void SetPrime()</span><br><span class="line">&#123;</span><br><span class="line">	int i,j;</span><br><span class="line">	len &#x3D; 0;</span><br><span class="line">	memset(isPrime,true,sizeof(isPrime));</span><br><span class="line">	for(i&#x3D;2; i&lt;&#x3D;N; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		if(isPrime[i])</span><br><span class="line">		&#123;</span><br><span class="line">			Prime[len++] &#x3D; i;</span><br><span class="line">			for(j&#x3D;i+i; j&lt;&#x3D;N; j +&#x3D; i)</span><br><span class="line">				isPrime[j] &#x3D; false;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">int main()</span><br><span class="line">&#123;</span><br><span class="line">	SetPrime();</span><br><span class="line">	int i;</span><br><span class="line">	for(i&#x3D;0; i&lt;len; ++i)</span><br><span class="line">		cout &lt;&lt; Prime[i] &lt;&lt;&#39; &#39;;</span><br><span class="line">	cout &lt;&lt; endl;</span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>3.用动态规划进行素数筛选</strong></p>
<p>这种办法较之上面的办法在效率上没有改进，几乎效率相同，但是思路很新颖，而且可以省下上面的isPrime[]数组的</p>
<p>不必要开销。这种办法用到一个知识。即如果我们已经知道线性表的前边k个数中一共有m个素数(2,3,5,7…)，假定对于第k+1个元素，如果Array[k+1]不能被前m个素数整除，说明Array[k+1]是素数，新增之，如果Array[k+1]能被前m个素数中的某一个素数整除，则说明Array[k+1]不是素数，可以排除之，继续往后迭代，直至到达区间的末尾。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;Dynamic Programming find primes</span><br><span class="line">&#x2F;&#x2F;first step : find Status Prime[0] &#x3D; 2,</span><br><span class="line">&#x2F;&#x2F;second step: find the Transfer formula,</span><br><span class="line">&#x2F;&#x2F;when the number A[i] can % prime[0...i] &#x3D;&#x3D; 0,</span><br><span class="line">&#x2F;&#x2F;it&#39;s not a prime,else it is a prime.</span><br><span class="line">int prime[50000];</span><br><span class="line">int pLen;</span><br><span class="line">void SetPrime()&#x2F;&#x2F;dp set prime</span><br><span class="line">&#123;</span><br><span class="line">	int i,j;</span><br><span class="line">	pLen &#x3D; 1;</span><br><span class="line">	bool isPrime;</span><br><span class="line">	prime[0] &#x3D; 2;</span><br><span class="line">	for (i&#x3D;3; i&lt;50000; i +&#x3D; 2)</span><br><span class="line">	&#123;</span><br><span class="line">		isPrime &#x3D; true; &#x2F;&#x2F;assume it&#39;s a prime</span><br><span class="line">		for(j&#x3D;0; j&lt;pLen; ++j)</span><br><span class="line">		&#123;</span><br><span class="line">			if ( (i%prime[j]) &#x3D;&#x3D; 0 )</span><br><span class="line">			&#123;</span><br><span class="line">				isPrime &#x3D; false; &#x2F;&#x2F;if i mod prime[j] &#x3D;&#x3D;0,than it&#39;s not a prime</span><br><span class="line">				break;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		if ( isPrime )</span><br><span class="line">			prime[pLen++] &#x3D; i;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.工程方法筛选素数<br>如果我们需要经常用到素数表，为何要每用一次就调用一次函数呢？直接将素数表打印到文件中，到用时再直接读取不就可以了吗？</p>
<p>下面是[2,5000]内的素数表： </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">2 3 5 7 11 13 17 19 23 29 31 37 41 43 47</span><br><span class="line">53 59 61 67 71 73 79 83 89 97 101 103 107 109 113</span><br><span class="line">127 131 137 139 149 151 157 163 167 173 179 181 191 193 197</span><br><span class="line">199 211 223 227 229 233 239 241 251 257 263 269 271 277 281</span><br><span class="line">283 293 307 311 313 317 331 337 347 349 353 359 367 373 379</span><br><span class="line">383 389 397 401 409 419 421 431 433 439 443 449 457 461 463</span><br><span class="line">467 479 487 491 499 503 509 521 523 541 547 557 563 569 571</span><br><span class="line">577 587 593 599 601 607 613 617 619 631 641 643 647 653 659</span><br><span class="line">661 673 677 683 691 701 709 719 727 733 739 743 751 757 761</span><br><span class="line">769 773 787 797 809 811 821 823 827 829 839 853 857 859 863</span><br><span class="line">877 881 883 887 907 911 919 929 937 941 947 953 967 971 977</span><br><span class="line">983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069</span><br><span class="line">1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187</span><br><span class="line">1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291</span><br><span class="line">1297 1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 1423 1427</span><br><span class="line">1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511</span><br><span class="line">1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613</span><br><span class="line">1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709 1721 1723 1733</span><br><span class="line">1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867</span><br><span class="line">1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987</span><br><span class="line">1993 1997 1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087</span><br><span class="line">2089 2099 2111 2113 2129 2131 2137 2141 2143 2153 2161 2179 2203 2207 2213</span><br><span class="line">2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297 2309 2311 2333</span><br><span class="line">2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411 2417 2423</span><br><span class="line">2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543 2549 2551 2557</span><br><span class="line">2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663 2671 2677 2683 2687</span><br><span class="line">2689 2693 2699 2707 2711 2713 2719 2729 2731 2741 2749 2753 2767 2777 2789</span><br><span class="line">2791 2797 2801 2803 2819 2833 2837 2843 2851 2857 2861 2879 2887 2897 2903</span><br><span class="line">2909 2917 2927 2939 2953 2957 2963 2969 2971 2999 3001 3011 3019 3023 3037</span><br><span class="line">3041 3049 3061 3067 3079 3083 3089 3109 3119 3121 3137 3163 3167 3169 3181</span><br><span class="line">3187 3191 3203 3209 3217 3221 3229 3251 3253 3257 3259 3271 3299 3301 3307</span><br><span class="line">3313 3319 3323 3329 3331 3343 3347 3359 3361 3371 3373 3389 3391 3407 3413</span><br><span class="line">3433 3449 3457 3461 3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539</span><br><span class="line">3541 3547 3557 3559 3571 3581 3583 3593 3607 3613 3617 3623 3631 3637 3643</span><br><span class="line">3659 3671 3673 3677 3691 3697 3701 3709 3719 3727 3733 3739 3761 3767 3769</span><br><span class="line">3779 3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907</span><br><span class="line">3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013 4019</span><br><span class="line">4021 4027 4049 4051 4057 4073 4079 4091 4093 4099 4111 4127 4129 4133 4139</span><br><span class="line">4153 4157 4159 4177 4201 4211 4217 4219 4229 4231 4241 4243 4253 4259 4261</span><br><span class="line">4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363 4373 4391 4397 4409</span><br><span class="line">4421 4423 4441 4447 4451 4457 4463 4481 4483 4493 4507 4513 4517 4519 4523</span><br><span class="line">4547 4549 4561 4567 4583 4591 4597 4603 4621 4637 4639 4643 4649 4651 4657</span><br><span class="line">4663 4673 4679 4691 4703 4721 4723 4729 4733 4751 4759 4783 4787 4789 4793</span><br><span class="line">4799 4801 4813 4817 4831 4861 4871 4877 4889 4903 4909 4919 4931 4933 4937</span><br><span class="line">4943 4951 4957 4967 4969 4973 4987 4993 4999</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/algorithm/" rel="tag"># algorithm</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/20/%E6%A0%91%E3%80%81%E6%A3%AE%E6%9E%97%E4%B8%8E%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%BD%AC%E6%8D%A2/" rel="next" title="树、森林与二叉树的转换">
                <i class="fa fa-chevron-left"></i> 树、森林与二叉树的转换
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/20/%E7%BC%96%E7%A8%8B%E4%B9%8B%E7%BE%8E%E5%B0%86%E5%B8%85%E4%B8%8D%E7%85%A7%E9%9D%A2/" rel="prev" title="编程之美将帅不照面">
                编程之美将帅不照面 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LinRaise</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LinRaise</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
